package com.ljtxxhwj.myblob.service.impl;

import com.ljtxxhwj.myblob.entity.Comment;
import com.ljtxxhwj.myblob.mapper.CommentMapper;
import com.ljtxxhwj.myblob.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    private final CommentMapper commentMapper;

    @Autowired
    public CommentServiceImpl(CommentMapper commentMapper) {
        this.commentMapper = commentMapper;
    }

    @Override
    public List<Comment> getCommentsByArticleId(Integer articleId) {
        return commentMapper.selectCommentsByArticleId(articleId);
    }

    @Override
    public void addComment(Comment comment) {

        // Get the current date in LocalDate
        LocalDate localDate = LocalDate.now();

        // Convert to java.sql.Date
        java.sql.Date sqlDate = java.sql.Date.valueOf(localDate);

        // Set the comment date
        comment.setCommentDate(sqlDate);
        commentMapper.insertComment(comment);
    }

    @Override
    public Comment getCommentById(Integer commentId) {
        return commentMapper.selectCommentById(commentId);
    }

    @Override
    public void updateCommentContent(Integer commentId, String newContent) {
        commentMapper.updateCommentContent(commentId, newContent);
    }

    @Override
    public void deleteCommentById(Integer commentId) {
        commentMapper.deleteCommentById(commentId);
    }

    @Override
    public List<Comment> getAllComments() {
        return commentMapper.selectAllComments();
    }
    @Override
    public List<Comment> getRepliesByCommentId(Integer commentId) {
        return commentMapper.selectRepliesByCommentId(commentId);
    }

    @Override
    public List<Comment> getCommentWithAllReplies(Integer commentId) {
        List<Comment> allReplies = new ArrayList<>();
        List<Comment> replies = getRepliesByCommentId(commentId);
        if (replies != null) {
            for (Comment reply : replies) {
                allReplies.add(reply);
                // 递归获取子评论的所有回复
                allReplies.addAll(getCommentWithAllReplies(reply.getCommentId()));
            }
        }
        return allReplies;
    }

    @Override
    public List<Comment> getCommentOnMe(int userId) {
        return  commentMapper.selectCommentOnMe(userId);
    }
}